<?php

namespace app\api\controller;

use app\common\controller\BaseApi;
use app\common\models\Coin;
use app\common\models\CoinOrder;
use app\common\models\QbRecord;
use app\common\models\SysConfig;
use app\common\service\TencentTopUpService;

class Activity extends BaseApi
{
    // 获取兑换活动规则
    public function getRole()
    {
        $this->verifyToken();
        $sys_config = new SysConfig();
        $config_data = $sys_config->getActivityInfo();
        if (empty($config_data)){
            $this->jsonError();
        }
        // 获取当前累计充值多少平台币
        $coin_order = new CoinOrder();
        $top_up = $coin_order->topUpTotal($config_data, $this->userId);
        $disabled_arr = [];
        if (!empty($config_data['activity_money'])){
            foreach ($config_data['activity_money'] as $val){
                $disabled_arr[$val['key']] = $val['value'];
            }
        }
        // 获取当前用户是否已经兑换
        $qb_record = new QbRecord();
        if (!empty($config_data['activity_discount'])){
            foreach ($config_data['activity_discount'] as &$val){
                $is_use = 0;
                if ($qb_record->getIsUse($config_data, $this->userId, $val['key'])){
                    $is_use = 1;
                }
                $val['is_use'] = $is_use;
                $is_disabled = 1;
                if (floatval($top_up) > floatval($disabled_arr[$val['key']])){
                    $is_disabled = 0;
                }
                $val['is_disabled'] = $is_disabled;
            }
        }
        $config_data['top_up'] = floatval($top_up);
        // 获取当前帐号平台币
        $coin_model = new Coin();
        $config_data['coin'] = $coin_model->getCoin($this->userId);

        $this->jsonResult($config_data);
    }

    public function qbTopUp()
    {
        $this->require = ['account', 'number', 'is_activity'];
        $this->verifyParam();
        $this->verifyToken();
        if (intval($this->data['account']) == 0 || intval($this->data['number']) == 0){
            $this->jsonFail('兑换失败');
        }
        // 获取当前账号余额
        $balance = TencentTopUpService::getBalance();
        if (floatval($balance) < intval($this->data['number'])){
            $this->jsonFail('兑换失败，兑换次数已抢完');
        }
        $qb_record = new QbRecord();
        $rows = $qb_record->topUp($this->data);
        if (!$rows){
            $this->jsonError($qb_record->getError());
        }
        // 发送API充值QB求请
        $rest = TencentTopUpService::qbPay($rows['order_code'], $rows['number'], $rows['account']);
        if (!$rest){
            $remark = TencentTopUpService::getError();
            $rows['remark'] = $remark;
            $rows['status'] = $qb_record::EXCHANGE_FAIL;
            $qb_record->topUpResult($rows);
            $this->jsonError('兑换失败');
        }
        $this->jsonResult($rows,'兑换成功');
    }
}